package org.example.steamshop.controller;

import org.example.steamshop.model.CartItem;
import org.example.steamshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/cart")
    public String cart(Model model, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }
        List<CartItem> list = cartService.getCartItems(userId);
        model.addAttribute("cartItems", list);

        return "cart";
    }


    // 添加游戏到购物车
    @PostMapping("/cart/add/{gameId}")
    public String addToCart(@PathVariable Long gameId, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }
        cartService.addToCart(userId, gameId);
        return "redirect:/cart";
    }

    @Transactional
    @PostMapping("/cart/remove/{gameId}")
    public String removeFromCart(@PathVariable Long gameId, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }

        cartService.removeFromCart(userId, gameId);
        return "redirect:/cart";
    }

    @Transactional
    @PostMapping("/cart/update/{gameId}")
    public String updateCartItemQuantity(
            @PathVariable Long gameId,
            @RequestParam int quantity,  // 接收表单提交的 quantity
            HttpSession session
    ) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return "redirect:/login";
        }

        if (quantity < 1) {
            // 可以返回错误页面或提示信息
            return "redirect:/cart?error=invalid_quantity";
        }

        cartService.updateCartItemQuantity(userId, gameId, quantity);
        return "redirect:/cart";  // 更新后刷新购物车页面
    }



}